import React, { useEffect, useCallback, useRef } from 'react';
import { Modal, Drawer } from 'antd';

/**
 * 响应式通用弹框组件，支持浏览器历史记录控制
 * @param {React.ReactNode} children - 弹框内容
 * @param {boolean} open - 显示状态
 * @param {function} onOpenChange - 状态变化回调
 * @param {boolean} isPc - 是否为PC端，true显示Modal，false显示Drawer
 */
export default ({
    children,
    open = false,
    onOpenChange,
    isPc = true,
    ...props
}) => {
    // 使用ref保存最新值，避免闭包问题
    const openRef = useRef(open);
    const onOpenChangeRef = useRef(onOpenChange);
    const hasAddedHistoryRef = useRef(false);
    const isClosingByPopstateRef = useRef(false);
    const isProcessingRef = useRef(false);
    
    // 同步更新ref值
    openRef.current = open;
    onOpenChangeRef.current = onOpenChange;

    // 关闭弹框处理函数
    const handleClose = useCallback(() => {
        // 防止重复处理
        if (isProcessingRef.current) return;
        
        // 主动关闭时，先回退移除历史记录，再关闭弹框
        if (hasAddedHistoryRef.current && !isClosingByPopstateRef.current) {
            isProcessingRef.current = true;
            hasAddedHistoryRef.current = false;
            window.history.replaceState(null, '', window.location.href);
            window.history.back(); // 这会触发popstate事件来关闭弹框
        } else {
            onOpenChangeRef.current?.(false);
        }
    }, []);

    // 管理历史记录状态
    useEffect(() => {
        if (open && !hasAddedHistoryRef.current && !isProcessingRef.current) {
            // 弹框打开时添加历史记录
            window.history.pushState({ dialogOpen: true }, '', window.location.href);
            hasAddedHistoryRef.current = true;
        } else if (!open) {
            // 弹框关闭时重置所有标记
            if (hasAddedHistoryRef.current && !isClosingByPopstateRef.current) {
                hasAddedHistoryRef.current = false;
            }
            // 重置所有处理标记
            isClosingByPopstateRef.current = false;
            isProcessingRef.current = false;
            window.history.replaceState(null, '', window.location.href);
        }
    }, [open]);

    // 监听浏览器前进后退事件
    useEffect(() => {
        const handlePopState = (event) => {
            // 回退时如果弹框是打开的就关闭
            if (openRef.current && (hasAddedHistoryRef.current || isProcessingRef.current)) {
                isClosingByPopstateRef.current = true;
                hasAddedHistoryRef.current = false;
                isProcessingRef.current = false;
                onOpenChangeRef.current?.(false);
                window.history.replaceState(null, '', window.location.href);
            }
        };

        window.addEventListener('popstate', handlePopState);

        return () => {
            window.removeEventListener('popstate', handlePopState);
        };
    }, []);

    // PC端显示Modal
    if (isPc) {
        return (
            <Modal
                title={null}
                footer={null}
                open={open}
                onCancel={handleClose}
                {...props}
            >
                {children}
            </Modal>
        );
    }

    // 移动端显示Drawer
    return (
        <Drawer
            title={null}
            footer={null}
            open={open}
            onClose={handleClose}
            {...props}
        >
            {children}
        </Drawer>
    );
};
